package com.webwork.mood.record.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.webwork.mood.record.dao.AwardRateDao;
import com.webwork.mood.record.dataobject.AwardInfo;
import com.webwork.mood.record.service.DrawAwardService;
import com.webwork.mood.util.Paging;
import com.webwork.mood.util.StrManager;

@Service
public class DrawAwardServiceImpl implements DrawAwardService {

	@Autowired
	private AwardRateDao awardRateDao;
	
	@Override
	public void insert(AwardInfo award) {
		awardRateDao.insert(award);
	}

	@Override
	public void update(AwardInfo award) {
		awardRateDao.update(award);
	}

	@Override
	public void delete(AwardInfo award) {
		awardRateDao.delete(award.getAwardName(), award.getCount());
	}
	
	@Override
	public List<AwardInfo> query(AwardInfo award) {
		return this.query(award, new Paging(0, 0));
	}
	
	@Override
	public List<AwardInfo> query(AwardInfo award, Paging page) {
		return awardRateDao.query(award, page.getCurrPage(), page.getPageSize());
	}
	
	@Override
	public AwardInfo get(String awardName) {
		if (StrManager.isEmpty(awardName)) {
			return null;
		}
		AwardInfo queryObj = new AwardInfo();
		queryObj.setAwardName(awardName);
		List<AwardInfo> awards = this.query(queryObj);
		if (awards != null && awards.size() > 0) {
			if (awards.size() > 1) {
				System.out.println("存在不止一条记录!");
			} else {
				return awards.get(0);
			}
		} else {
			System.out.println("找不到该记录!");
		}
		return null;
	}

	@Override
	public int count(AwardInfo record) {
		return awardRateDao.count(record);
	}
	
	@Override
	public AwardInfo generateAward() {
		List<AwardInfo> initData = this.query(new AwardInfo());
		long result = randomnum(1, 100);
		float line = 0;
		float temp = 0;
		AwardInfo returnobj = null;
		for (int i = 0; i < initData.size(); i++) {
			AwardInfo obj2 = initData.get(i);
			float c = obj2.getRate();
			temp = temp + c;
			line = 100 - temp;
			if (c != 0) {
				if (result > line && result <= (line + c)) {
					returnobj = obj2;
					break;
				}
			}
		}
		return returnobj;
	}

	/**
	 * 获取2个值之间的随机数
	 * @param smin
	 * @param smax
	 * @return
	 */
	private long randomnum(int smin, int smax) {
		int range = smax - smin;
		double rand = Math.random();
		return (smin + Math.round(rand * range));
	}

}
